package controllers

import (
	"blog/models"
	"crypto/md5"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"github.com/go-sdk/upyun"
	"math/rand"
	"path"
	"strconv"
	"time"
)

type BannerController struct {
	beego.Controller
}

//列表
func (c*BannerController)  List(){
	o := orm.NewOrm()
	banner := new(models.Banner)
	qs := o.QueryTable(banner)
	var data []models.Banner
	_,err := qs.OrderBy("id").All(&data)
	if err != nil {
		beego.Info("错误信息:",err)
		return
	}
	c.Data["json"] = map[string]interface{}{"code":0,"msg":"请求成功","count":0,"data":data}
	c.ServeJSON();
	return
}

//新增
func (c*BannerController) Add(){
	o := orm.NewOrm()
	title := c.GetString("title")
	image := c.GetString("image")
	bannerType := c.GetString("type")
	url := c.GetString("url")

	var startTime = "2006-01-02 15:04:05"

	bType, _ :=strconv.Atoi(bannerType)
	nowDate := time.Now().Format("2006-01-02 15:04:05")
	zhTime, _ := time.Parse(startTime,nowDate);

	var banner models.Banner
	banner.Title = title
	banner.Image = image
	banner.Type = bType
	banner.Url = url
	banner.Created_at = zhTime
	_, err := o.Insert(&banner)
	if err != nil {
		beego.Info("错误信息:",err)
		return
	}
	c.Data["json"] = map[string]interface{}{"code":200,"msg":"请求成功","data":""}
	c.ServeJSON()
	return
}

//上传文件
func (c*BannerController) Upload() {
	//获取上传文件
	file, header, err := c.GetFile("files")
	if err != nil {
		beego.Info("文件上传失败,错误信息:",err)
		return
	}
	ext := path.Ext(header.Filename)
	//验证后缀名是否符合要求
	var AllowExtMap map[string]bool = map[string]bool{
		".jpg":true,
		".jpeg":true,
		".png":true,
	}
	if _,ok:=AllowExtMap[ext];!ok{
		beego.Info("后缀名不符合上传文件要求,错误信息:",err)
		return
	}

	//构造文件名称
	rand.Seed(time.Now().UnixNano())
	randNum := fmt.Sprintf("%d", rand.Intn(9999)+1000 )
	hashName := md5.Sum( []byte( time.Now().Format("2006_01_02_15_04_05_") + randNum ) )

	fileName := fmt.Sprintf("%x",hashName) + ext

	defer file.Close()//关闭上传的文件，不然的话会出现临时文件不能清除的情况
	up := upyun.NewUpYun(&upyun.UpYunConfig{
		Bucket:beego.AppConfig.String("Bucket"),
		Operator:beego.AppConfig.String("Operator"),
		Password:beego.AppConfig.String("Password"),
	})

	err = up.Put(&upyun.PutObjectConfig{
		Path:"/image/" + time.Now().Format("2006-01-02/") + fileName,
		Reader:file,
	})
	if err != nil {
		beego.Info("文件上传又拍云OSS失败,错误信息",err)
		return
	}
	upyunPATH := beego.AppConfig.String("upyun") + "/image/" + time.Now().Format("2006-01-02/") + fileName
	jsonStr := map[string]interface{}{"src":upyunPATH}
	c.Data["json"] = map[string]interface{}{"code":200,"msg":"请求成功","data":jsonStr}
	c.ServeJSON()
	return
}

//删除
func (c*BannerController) Delete() {
	o := orm.NewOrm()
	id := c.GetString("id")
	intId, _ := strconv.Atoi(id)
	banner := models.Banner{Id:intId}
	_, err := o.Delete(&banner);
	if err != nil {
		beego.Info("错误信息:",err)
		return
	}
	c.Data["json"] = map[string]interface{}{"code":200,"msg":"请求成功","data":""}
	c.ServeJSON()
	return
}


